home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 7 / Apprentice-Release7.iso / Source Code / C / Applications / Python 1.4 / Python 1.4 source / Mac / Lib / py_resource.py < prev    next >
Encoding:
Python Source  |  1996-07-10  |  1.8 KB  |  77 lines  |  [TEXT/Pyth]

  1. """Creation of PYC resources"""
  2. import os
  3. import Res
  4. import __builtin__
  5.  
  6. READ = 1
  7. WRITE = 2
  8. smAllScripts = -3
  9.  
  10. def Pstring(str):
  11.     """Return a pascal-style string from a python-style string"""
  12.     if len(str) > 255:
  13.         raise ValueError, 'String too large'
  14.     return chr(len(str))+str
  15.     
  16. def create(dst, creator='Pyth'):
  17.     """Create output file. Return handle and first id to use."""
  18.     
  19.     try:
  20.         os.unlink(dst)
  21.     except os.error:
  22.         pass
  23.     Res.FSpCreateResFile(dst, creator, 'rsrc', smAllScripts)
  24.     return open(dst)
  25.     
  26. def open(dst):
  27.     output = Res.FSpOpenResFile(dst, WRITE)
  28.     Res.UseResFile(output)
  29.     return output
  30.  
  31. def writemodule(name, id, data, type='PYC '):
  32.     """Write pyc code to a PYC resource with given name and id."""
  33.     # XXXX Check that it doesn't exist
  34.     res = Res.Resource(data)
  35.     res.AddResource(type, id, name)
  36.     res.WriteResource()
  37.     res.ReleaseResource()
  38.         
  39. def frompycfile(file, name=None):
  40.     """Copy one pyc file to the open resource file"""
  41.     if name == None:
  42.         d, name = os.path.split(file)
  43.         name = name[:-4]
  44.     id = findfreeid()
  45.     writemodule(name, id, __builtin__.open(file, 'rb').read())
  46.     return id, name
  47.  
  48. def frompyfile(file, name=None):
  49.     """Compile python source file to pyc file and add to resource file"""
  50.     import py_compile
  51.     
  52.     py_compile.compile(file)
  53.     file = file +'c'
  54.     return frompycfile(file, name)    
  55.  
  56. # XXXX Note this is incorrect, it only handles one type and one file....
  57.  
  58. _firstfreeid = None
  59.  
  60. def findfreeid(type='PYC '):
  61.     """Find next free id-number for given resource type"""
  62.     global _firstfreeid
  63.     
  64.     if _firstfreeid == None:
  65.         Res.SetResLoad(0)
  66.         highest = 511
  67.         num = Res.Count1Resources(type)
  68.         for i in range(1, num+1):
  69.             r = Res.Get1IndResource(type, i)
  70.             id, d1, d2 = r.GetResInfo()
  71.             highest = max(highest, id)
  72.         Res.SetResLoad(1)
  73.         _firstfreeid = highest+1
  74.     id = _firstfreeid
  75.     _firstfreeid = _firstfreeid+1
  76.     return id
  77.